const lodash = require('lodash')
const loginFns = require("../common/login")
import { pageFns } from '../utils/pageHelper'
import { funcFns } from '@/puppeteer/utils/funtion'
import { ArticleDao } from '@/dao/articleDao'


const SELECTORS = { "MASKWRAPPER": [".byte-drawer-header > div > div > span"], "INPUTTEXT": [".ProseMirror"], "CLICKIMAGE": ["span::-p-text(\"图片\")"], "CLICKVIDEO": ["span::-p-text(\"视频\")"], "INPUTIMAGE": "input[type=\"file\"]", "SOURCEFROM": ".byte-checkbox-wrapper span::-p-text('个人观点，仅供参考')", "UPLOADIMAGECONFIRM": [".footer .confirm-btns button:nth-child(2)"], "UPLOADVIDEOCONFIRM": ["#wtt-video-card div::-p-text(\"更换封面\")"], "PUBLISH": [".footer-wrap span::-p-text(\"发布\")", ".footer-wrap span::-p-text(\"发布\")"] }
// 发布
async function startPost(page, content, files, selectors) {
    let res = await pageFns.deepRetry(selectors.MASKWRAPPER, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await page.click(selector)
    }, { page: page, timeout: 1000 })
    if (res.err) return res

    res = await pageFns.deepRetry(selectors.INPUTTEXT, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await page.evaluate((selector, className) => {
            const element = document.querySelector(selector);
            if (element) {
                element.classList.add(className);
            }
        }, selector, "ProseMirror-focused");
        await page.type(selector, content)
    }, { page: page, timeout: 1000 })
    if (res.err) return res
    /**
     * @description JUDGE THE MEDIA TYPE
     */
    let postFiles = files.filter(item => item.match(/\.(mp4)$/))
    if (postFiles.length > 0) {
        /**
        * @description GOTO UPLOAD VEDIO BOARD
        */
        let res = await pageFns.deepRetry(selectors.CLICKVIDEO, page, async (selector, page) => {
            await page.waitForSelector(selector)
            await page.click(selector)
        }, { page: page, timeout: 1000 })
        if (res.err) return res
        /**
        * @description UPLOAD IMAGE STATUS METHOD
        */
        await page.waitForSelector(selectors.INPUTIMAGE)
        await pageFns.fileUpload({ page, element: selectors.INPUTIMAGE, files: postFiles })
        res = await pageFns.deepRetry(selectors.UPLOADVIDEOCONFIRM, page, async (selector, page) => {
            await page.waitForSelector(selector)
        }, { page: page, timeout: 1000 })
        if (res.err) return res
    } else {
        /**
        * @description GOTO UPLOAD IMAGE BOARD
        */
        let res = await pageFns.deepRetry(selectors.CLICKIMAGE, page, async (selector, page) => {
            await page.waitForSelector(selector)
            await page.click(selector)
        }, { page: page, timeout: 1000 })
        if (res.err) return res
        /**
        * @description UPLOAD IMAGE STATUS METHOD
        */
        postFiles = files.filter(item => item.match(/\.(mp4)$/))
        if (postFiles.length > 0) {
            postFiles = files.length <= 0 ? files : files.slice(0, 1)
        } else {
            postFiles = files.filter(item => item.match(/\.(png|jpeg|jpg)$/))
            postFiles = files.length <= 4 ? files : files.slice(0, 4)
        }
        await page.waitForSelector(selectors.INPUTIMAGE)
        await pageFns.fileUpload({ page, element: selectors.INPUTIMAGE, files: postFiles })
        res = await pageFns.deepRetry(selectors.UPLOADIMAGECONFIRM, page, async (selector, page) => {
            await page.waitForSelector(selector)
            await page.waitForFunction((selector, className) => {
                const element = document.querySelector(selector);
                return !element || !element.classList.contains(className);
            }, {}, selector, 'byte-btn-disabled')
            await page.click(selector)
        }, { page: page })
        if (res.err) return res
    }
    /**
     * @description SELECT SOURCE METHOD
     */
    await page.waitForSelector(selectors.SOURCEFROM)
    await page.click(selectors.SOURCEFROM)
    /**
     * @description WAIT STATUS METHOD
     */
    res = await pageFns.deepRetry(selectors.PUBLISH, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await page.click(selector)
        await page.waitForNavigation({ waitUntil: "domcontentloaded" })
    }, { page: page, timeout: 1000, wait: 10000 })

    if (res.err) {
        return res
    }
    return { data: "发布成功" }
}

const LOGINS = {
    LOGINBTNS: ['li[aria-label="账密登录"]'],
    USERNAMES: ['.web-login-normal-input input[name="normal-input"]'],
    NEXTSTEPS: [],
    PASSWORDS: ['.web-login-button-input input[name="button-input"]'],
    AGREEMENTBTNS: ['.web-login-confirm-info span[role="checkbox"]'],
    COMFIRMBTNS: ['.web-login-account-password__button-wrapper .web-login-button', '.web-login-account-password__button-wrapper button[type="submit"]'],
    UNLOGINFLAGS: ['li[aria-label="账密登录"]']
}

async function goPost(page, task, article, rule) {
    let selectors = JSON.parse(rule.codeRule)
    if (lodash.isEmpty(selectors)) {
        return { err: "找不到发布规则:" + task.id }
    }
    let res = await loginFns.checkLogin(page, task, LOGINS)
    if (res.err) {
        console.log("goPost.checkLogin", res)
        return res
    }
    // 收集图片
    try {
        let dataFields = JSON.parse(task.dataFields)
        if (lodash.isEmpty(dataFields)) {
            return { err: "没有指定的数据" }
        }
        let aiResult = JSON.parse(article.aiResult)
        let contents = []
        for (let dataField of dataFields) {
            contents.push(aiResult[task.lang][dataField])
        }
        console.log(dataFields, article, task.lang)
        let images = funcFns.getImages(ArticleDao.folderPath(article))
        return await startPost(page, contents.join("."), images, selectors)
    } catch (err) {
        console.log("goPost", err)
        return { err: err }
    }
}

export { goPost }